package mathsys;

import java.io.*;
import java.util.*;

public class MathExerciseGeneratorV3 {
    // 存储已生成的算式，用于去重
    private static Set<String> generatedExpressions = new HashSet<>();

    // 生成指定范围内的随机整数
    private static int getRandomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    // 生成带答案的加减法算式（确保不重复）
    private static Map.Entry<String, Integer> generateUniqueExercise() {
        while (true) {
            int num1 = getRandomNumber(0, 100);
            int num2 = getRandomNumber(0, 100);
            int operator = getRandomNumber(0, 1); // 0:加法, 1:减法
            String expression;
            int result;

            if (operator == 0) { // 加法
                // 确保和不超过100
                if (num1 + num2 > 100) {
                    continue;
                }
                // 标准化加法表达式（小的数在前，避免3+5和5+3被视为不同）
                if (num1 > num2) {
                    int temp = num1;
                    num1 = num2;
                    num2 = temp;
                }
                expression = num1 + " + " + num2 + " = ?";
                result = num1 + num2;
            } else { // 减法
                // 确保差不小于0
                if (num1 < num2) {
                    continue;
                }
                expression = num1 + " - " + num2 + " = ?";
                result = num1 - num2;
            }

            // 检查是否已存在该算式
            if (!generatedExpressions.contains(expression)) {
                generatedExpressions.add(expression);
                return new AbstractMap.SimpleEntry<>(expression, result);
            }
        }
    }

    // 生成HTML文件
    private static void generateHTML(List<Map.Entry<String, Integer>> exercises) {
        try (PrintWriter out = new PrintWriter(new FileWriter("math_exercises_v0.3.html"))) {
            out.println("<!DOCTYPE html>");
            out.println("<html lang=\"zh-CN\">");
            out.println("<head>");
            out.println("    <meta charset=\"UTF-8\">");
            out.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
            out.println("    <title>加减法口算练习系统-v0.3</title>");
            out.println("    <style>");
            out.println("        body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }");
            out.println("        h1 { color: #333; text-align: center; }");
            out.println("        .stats { text-align: center; color: #666; margin: 10px 0 20px; }");
            out.println("        .exercise-container { margin: 30px auto; display: grid;");
            out.println("            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));");
            out.println("            gap: 15px; }");
            out.println("        .exercise { font-size: 16px; padding: 12px; border: 1px solid #ddd;");
            out.println("            border-radius: 5px; background-color: #f9f9f9; }");
            out.println("        .addition { border-left: 4px solid #4CAF50; }"); // 加法标识色
            out.println("        .subtraction { border-left: 4px solid #2196F3; }"); // 减法标识色
            out.println("        .answer { color: #666; font-size: 14px; margin-top: 5px; display: none; }");
            out.println("        .controls { text-align: center; margin: 20px; }");
            out.println("        button { padding: 8px 16px; font-size: 16px; cursor: pointer;");
            out.println("            background-color: #4CAF50; color: white; border: none; border-radius: 4px; margin: 0 5px; }");
            out.println("        button:hover { background-color: #45a049; }");
            out.println("        #hideBtn { background-color: #f44336; }");
            out.println("        #hideBtn:hover { background-color: #d32f2f; }");
            out.println("    </style>");
            out.println("    <script>");
            out.println("        function showAnswers() {");
            out.println("            const answers = document.getElementsByClassName('answer');");
            out.println("            for (let ans of answers) ans.style.display = 'block';");
            out.println("        }");
            out.println("        function hideAnswers() {");
            out.println("            const answers = document.getElementsByClassName('answer');");
            out.println("            for (let ans of answers) ans.style.display = 'none';");
            out.println("        }");
            out.println("    </script>");
            out.println("</head>");
            out.println("<body>");
            out.println("    <h1>加减法口算练习系统-v0.3</h1>");

            // 统计加减法数量
            long additionCount = exercises.stream()
                    .filter(e -> e.getKey().contains("+"))
                    .count();
            long subtractionCount = exercises.size() - additionCount;

            out.println("    <div class=\"stats\">");
            out.println("        共" + exercises.size() + "题（加法：" + additionCount + "题，减法：" + subtractionCount + "题）");
            out.println("    </div>");

            out.println("    <div class=\"controls\">");
            out.println("        <button onclick=\"showAnswers()\">显示答案</button>");
            out.println("        <button id=\"hideBtn\" onclick=\"hideAnswers()\">隐藏答案</button>");
            out.println("    </div>");
            out.println("    <div class=\"exercise-container\">");

            // 循环生成习题
            int count = 1;
            for (Map.Entry<String, Integer> exercise : exercises) {
                String expression = exercise.getKey();
                int answer = exercise.getValue();
                String typeClass = expression.contains("+") ? "addition" : "subtraction";

                out.println("        <div class=\"exercise " + typeClass + "\">");
                out.println("            <span class=\"number\">" + count + ". </span>");
                out.println("            <span class=\"expression\">" + expression + "</span>");
                out.println("            <div class=\"answer\">答案: " + answer + "</div>");
                out.println("        </div>");
                count++;
            }

            out.println("    </div>");
            out.println("</body>");
            out.println("</html>");

            System.out.println("习题已生成，请打开 math_exercises_v0.3.html 文件查看");
        } catch (IOException e) {
            System.err.println("生成HTML文件时出错: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        int totalCount = 50;
        // 确保至少有1道加法和1道减法
        if (totalCount < 2) {
            System.err.println("题目数量不能少于2道");
            return;
        }

        List<Map.Entry<String, Integer>> exercises = new ArrayList<>();
        generatedExpressions.clear(); // 清空历史记录

        // 先确保至少生成1道加法和1道减法
        // 生成加法
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("+")) {
                exercises.add(exercise);
                break;
            }
        }
        // 生成减法
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("-")) {
                exercises.add(exercise);
                break;
            }
        }

        // 生成剩余题目
        for (int i = 2; i < totalCount; i++) {
            exercises.add(generateUniqueExercise());
        }

        // 打乱题目顺序
        Collections.shuffle(exercises);

        // 生成HTML页面
        generateHTML(exercises);
    }
}